package com.example.wxy.bbtapp.Common;

import android.content.Context;
import android.os.Environment;
import android.util.Log;


import com.example.wxy.bbtapp.DeviceService.CommandHelper;
import com.example.wxy.bbtapp.Startup.AppSettings;
import com.example.wxy.bbtapp.Models.RetrunValue.VerData;
import com.example.wxy.bbtapp.Service.BindService;
import com.example.wxy.bbtapp.myApplication;

import java.io.File;

/**
 * Created by yons on 2017/9/8.
 */

public class updater {

    public static File file = null;
    public static String url = "http://192.168.1.200/update.apk";

    public static void checkUpdate(Context c) {
        Log.d(AppSettings.DebugTag, "我进入点击在update里面啦");
        BindService.getVer(new httpCallBack<VerData>("获取更新包") {
            @Override
            public void onSuccess(VerData verData) {
                // 获取服务器版本号
                Log.d(AppSettings.DebugTag, "myApplication.AppVer:" + myApplication.AppVer);

                if (!verData.getAPKVersion().equals(myApplication.AppVer)) {
                    downLoad();
                } else {
                    Log.d(AppSettings.DebugTag, "checkUpdate server ver equals local ver");
                }
            }
        });
    }

    // 静默安装
    private static boolean clientInstall(String apkPath) {
        try {
            Runtime.getRuntime().exec("pm install -r " + apkPath);

            Log.d(AppSettings.DebugTag, "Install Update, apkPath:" + apkPath);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //
    public static void downLoad() {
        Thread thread;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                FileHelper.downLoadFile(url, "update.apk", Environment.getExternalStorageDirectory() + File.separator + "update");
                //clientInstall(file.getPath());
                String result = CommandHelper.execCommand("pm", "install", "-r", file.getPath());
                Log.d(AppSettings.DebugTag, "Install Updated, Message:" + result);
            }
        });
        thread.start();
    }
}
